package handler

import (
	"day1103/cache"
	"day1103/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var data []model.Article
	redis_key := "article_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
	return
}
func Detail(c *gin.Context) {
	var data model.Article
	redis_key := "article_detail"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
	return
}
func Comment(c *gin.Context) {
	aid, _ := strconv.Atoi(c.PostForm("aid"))
	content := c.PostForm("content")
	data := model.Comment{
		Aid:     aid,
		Content: content,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return
}
func CommentList(c *gin.Context) {
	var data []model.Comment
	redis_key := "article_comment_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Order("id desc").Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
	return
}
